package com.lx.util.secure.algorithm;

import com.lx.annotation.Note;
import com.lx.util.secure.algorithm.coder.CoderType;
import com.lx.util.secure.algorithm.coder.Encoder;
import lombok.Data;

import java.nio.charset.StandardCharsets;
import java.util.Map;

public abstract class SignAlgorithm<T extends SignAlgorithm> extends SecureAlgorithm<T> {

    @Note("签名算法")
    private String signAlgorithm;

    public SignAlgorithm() {
        setSignAlgorithm(defaultSignAlgorithm());
    }

    protected abstract String defaultSignAlgorithm();

    protected String getSignAlgorithm() {
        return signAlgorithm;
    }

    protected void setSignAlgorithm(String signAlgorithm) {
        this.signAlgorithm = signAlgorithm;
    }

    public T signAlgorithm(String signAlgorithm){
        this.signAlgorithm = signAlgorithm;
        return (T) this;
    }

    public abstract byte[] sign(byte[] bytes);

    public String sign(String data){
        return getCoderType().encodeToString(sign(data.getBytes(StandardCharsets.UTF_8)));
    }

    public String sign(final Map<String, String> params){
        return sign(createLinkString(params));
    }

    public String sign(final Map<String, String> params,String exclude, String connStr, boolean urlEncode, boolean skipEmpty){
        return sign(createLinkString(params,exclude,connStr,urlEncode,skipEmpty));
    }

    public abstract boolean verify(byte[] bytes, byte[] sign);

    public boolean verify(String data, String sign){
        return verify(data.getBytes(StandardCharsets.UTF_8),getCoderType().decode(sign));
    }

    public boolean verify(final Map<String,String> map, String sign){
        return verify(createLinkString(map),sign);
    }

}
